package models

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"fmt"
)

type Application struct {
	Id          string `json:"id"`
	Name        string `json:"name"`
	PrKey       string `json:"-"`     // 私钥（JSON 序列化时忽略）
	PuKey       string `json:"puKey"` // 公钥
	SerPuKey    string `json:"serPuKey"`
	CallbackUrl string `json:"callbackUrl"` // 回调地址
}

// GenerateID 生成唯一应用ID (UUID简化版)
func GenerateID() (string, error) {
	const length = 16 // 16字节 = 128位
	b := make([]byte, length)
	if _, err := rand.Read(b); err != nil {
		return "", fmt.Errorf("生成ID失败: %v", err)
	}
	return base64.URLEncoding.EncodeToString(b), nil
}

// GenerateKeyPair 生成RSA公私钥对
func GenerateKeyPair(bits int) (prKey, puKey string, err error) {
	privateKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return "", "", fmt.Errorf("密钥生成失败: %v", err)
	}

	// 编码私钥
	privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey)
	privateKeyPEM := pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: privateKeyBytes,
	})

	// 编码公钥
	publicKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
	if err != nil {
		return "", "", fmt.Errorf("公钥编码失败: %v", err)
	}
	publicKeyPEM := pem.EncodeToMemory(&pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: publicKeyBytes,
	})

	return string(privateKeyPEM), string(publicKeyPEM), nil
}

// GetDefaultKeyPair 获取默认强度的密钥对 (2048位)
func GetDefaultKeyPair() (string, string, error) {
	return GenerateKeyPair(2048)
}

// VerifyKeyPair 验证公私钥是否匹配
func VerifyKeyPair(prKey, puKey string) bool {
	block, _ := pem.Decode([]byte(prKey))
	if block == nil {
		return false
	}
	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return false
	}

	pubBlock, _ := pem.Decode([]byte(puKey))
	if pubBlock == nil {
		return false
	}
	pubKey, err := x509.ParsePKIXPublicKey(pubBlock.Bytes)
	if err != nil {
		return false
	}

	rsaPubKey, ok := pubKey.(*rsa.PublicKey)
	if !ok {
		return false
	}

	return privateKey.PublicKey.Equal(rsaPubKey)
}
